const PENDING = 'pending'; //等待状态
const FULFILLED = 'fulfilled'; //成功状态
const REJECTED = 'rejected'; //失败状态

class MyPromise {
  //Promise对象创建时，传入了一个执行器函数，使用构造函数接收此执行函数
  constructor(executor) {
    //Promise对象创建时,执行器函数立即执行，执行器函数的两个参数分别是函数resolve、reject
    executor(this.resolve, this.reject);
  }
  //当前实例对象的状态，默认为等待
  status = PENDING;
  //成功之后的值
  value = undefined;
  //失败之后的原因
  reason = undefined;
  //成功回调、失败回调,用于在异步情况下的回调存储
  successCallback = [];
  failCallback = [];

  //使用箭头函数定义resolve、reject，使resolve、reject函数内部的this指向实例对象，也就是Promise对象
  resolve = value => {
    //如果当前对象的状态不是等待，退出函数
    if (this.status !== PENDING) return;
    //将状态改为成功
    this.status = FULFILLED;
    //保存成功之后的值
    this.value = value;
    //判断成功回调是否存在  存在则调用
    while (this.successCallback.length) this.successCallback.shift()(this.value);
  }
  reject = reason => {
    //如果当前对象的状态不是等待，退出函数
    if (this.status !== PENDING) return;
    //将状态改为失败
    this.status = REJECTED;
    //保存失败之后的原因
    this.reason = reason;
    //判断失败回调是否存在  存在则调用
    while (this.failCallback.length) this.failCallback.shift()(this.reason);
  }
  //用来判断状态，被定义在原型对象中
  then(successCallback, failCallback) {
    //将then方法的参数变成可选参数
    successCallback = successCallback ? successCallback : value => value;
    failCallback = failCallback ? failCallback: reason => { throw reason };

    let promise = new MyPromise((resolve, reject) => {
      //判断状态
      if (this.status === FULFILLED) {
        setTimeout(() => {
          //实现将当前成功回调函数的值传递给下一个promise对象
          let callbackValue = successCallback(this.value)
          /**
           * 判断callbackValue是普通值还是对象，如果是普通值，直接调用resolve方法，传递给下一个promise对象
           * 如果是promise对象，根据promise对象返回的结果，决定是调用resolve还是reject
           */
          resolvePromise(promise, callbackValue, resolve, reject);
        }, 0);
      } else if (this.status === REJECTED) {
        failCallback(this.reason);
      } else { //异步情况下的等待状态
        //将成功回调和失败回调存储起来
        this.successCallback.push(successCallback);
        this.failCallback.push(failCallback);
      }
    });

    //确保每一个then方法都返回一个Promise对象
    return promise;
  }
  finally(callback) {
    //返回当前promise对象
    return this.then(value => {
      return MyPromise.resolve(callback()).then(() => value);
    }, reason => {
      return MyPromise.resolve(callback()).then(() => { throw reason });
    });
  }
  catch(failCallback) {
    return this.then(undefined, failCallback);
  }
  //定义一个静态方法all,接收一个数组，用于解决异步调用并发问题
  static all(array) {
    let result = [];
    let index = 0;
    return new MyPromise((resolve, reject) => {
      function addData(key, value) {
        result[key] = value;
        index++;
        if(index === array.length) {//确保异步操作执行完
          resolve(result);//将执行完的结果返回
        }  
      }
      for(let i = 0; i < array.length; i++) {
        //获取数组中的每一个值
        let current = array[i];
        if(current instanceof MyPromise) {//promise对象
          current.then(value => addData(i, value), reason => reject(reason));
        } else { //普通值
          addData(i, array[i]);//将普通值存入数组中
        }
      }
    });
  }
  //定义一个静态的resolve方法，接收一个参数
  static resolve(value) {
    //如果传入的参数是Promise对象，则直接返回
    if(value instanceof MyPromise) return value;
    //如果是普通值，则将普通值转为Promise对象
    return new MyPromise(resolve => resolve(value));
  }
}

function resolvePromise(promise, callbackValue, resolve, reject) {
  if (promise === callbackValue) {
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'));
  }
  //promise对象
  if (callbackValue instanceof MyPromise) {
    //根据callbackValue的值，决定是调用resolve还是reject
    callbackValue.then(resolve, reject);
    // callbackValue.then(value => resolve(value), reason => reject(reason));
  } else { //普通值
    resolve(callbackValue);
  }
}

module.exports = MyPromise;